﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace ExpressionToWhere
{
    /// <summary>
    /// worker.Name == name.Substring(0,3)+"999"中用来计算name.Substring(0,3)的值
    /// </summary>
    internal class ConstantMethodCallExpressionVisitor : ConstantExpressionVisitor
    {
        protected override Expression VisitMethodCall(MethodCallExpression node)
        {
            MethodInfo methodInfo = node.Method;
            object instance = null;
            object[] parameters = null;
            if (node.Object != null)
            {
                instance = ExpressionProcesser.GetConstant(node.Object);
            }
            if (node.Arguments != null && node.Arguments.Count > 0)
            {
                parameters = new object[node.Arguments.Count];
                for (int i = 0; i < node.Arguments.Count; i++)
                {
                    Expression expression = node.Arguments[i];
                    parameters[i] = ExpressionProcesser.GetConstant(expression);
                }
            }
            Value = methodInfo.Invoke(instance, parameters);
            return node;
        }
    }
}
